package com.hk.dyeyuesystem;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.hk.dyeyuesystem.db.DBOpenHelper;
import com.hk.dyeyuesystem.model.Book;
import com.hk.dyeyuesystem.util.DateUtil;
import com.hk.dyeyuesystem.util.ToastUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 预约图书控制层
 */
public class BorrowActivity extends Activity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

//    查询图书按钮和预约图书按钮
    private Button queryBook,borrowBook;
//    搜索图书名称或书号 归还日期
    private EditText borrowName,returnTime;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_borrow);
//        实例化
        dbOpenHelper = new DBOpenHelper(BorrowActivity.this,"db_book_system",null,1);

        queryBook = findViewById(R.id.query_book_btn);
        borrowBook = findViewById(R.id.borrow_book_btn);
        queryBook.setOnClickListener(this);
        borrowBook.setOnClickListener(this);

        //        检测登录是否正常
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
//        校验登录状态是否正常
        checkLogin(bundle);


    }

    /**
     * 校验登录状态是否正常
     * @param bundle 存储的登录账号信息
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void checkLogin(Bundle bundle) {
        if (Objects.isNull(bundle)) {
            toast = ToastUtil.toastHint(toast,BorrowActivity.this,"当前登录异常,请重新登录!");
            return;
        }
        if (Objects.nonNull(bundle)) {
            String loginId = (String) bundle.get("loginId");
            if (Objects.isNull(loginId) || loginId.equals("")) {
                toast = ToastUtil.toastHint(toast,BorrowActivity.this,"当前登录异常,请重新登录!");
                return;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.query_book_btn: // 查询图书
//                获取搜索的图书名称或书号
                borrowName = findViewById(R.id.borrow_name);
                String borrowName2 = borrowName.getText().toString();
                if (Objects.isNull(borrowName2) || borrowName2.equals("")) {
                    toast = ToastUtil.toastHint(toast,BorrowActivity.this,"请输入需要查询的书籍！");
                    break;
                }
//                数据库搜索数据
                Book book = searchBook(borrowName2);
//                获取到页面布局和文本控制权
                //                获取表格布局
                TableLayout tableLayout = findViewById(R.id.tabLayout);
//                左侧标题控制权
                TextView bookTitle = findViewById(R.id.book_title);
                TextView authorTitle = findViewById(R.id.author_title);
                TextView pressTitle = findViewById(R.id.press_title);
                TextView bookCountTitle = findViewById(R.id.book_count_title);
                TextView residueTitle = findViewById(R.id.residue_title);
                TextView returnTiTle = findViewById(R.id.return_title);
//                ID
                TextView bookId = findViewById(R.id.book_id);
//                隐藏此控件
                bookId.setVisibility(View.GONE);
//                右侧数据区域控制权
                TextView bookName = findViewById(R.id.book_name);
                TextView author = findViewById(R.id.author);
                TextView press = findViewById(R.id.press);
                TextView bookCount = findViewById(R.id.book_count);
                TextView residue = findViewById(R.id.residue);
                returnTime = findViewById(R.id.return_time);
                if (Objects.isNull(book)) {
//                    Initialize Layout
                    tableLayout.setBackgroundColor(0xCC0000);
                    //                左侧标题 清空
                    bookTitle.setText("");authorTitle.setText("");pressTitle.setText("");
                    bookCountTitle.setText("");residueTitle.setText("");bookId.setText("");
                    returnTiTle.setText("");
//                右侧数据 清空
                    bookName.setText("");author.setText("");press.setText("");
                    bookCount.setText("");residue.setText("");
                    Toast.makeText(BorrowActivity.this,"暂无相关书籍,后续会进行补充，请注意关注！",Toast.LENGTH_SHORT).show();
                    break;
                }

//                设置背景颜色为黄褐色
                tableLayout.setBackgroundColor(0xCCFFC107);
//                赋值
//                左侧标题
                bookTitle.setText("书名：");
                authorTitle.setText("作者：");
                pressTitle.setText("出版社：");
                bookCountTitle.setText("总数：");
                residueTitle.setText("剩余数量：");
                returnTiTle.setText("归还日期：");
//                ID
                bookId.setText(book.getId().toString());
//                右侧数据
                bookName.setText(book.getBookName());
                author.setText(book.getAuhtor());
                press.setText(book.getPress());
                bookCount.setText(book.getbookNum().toString());
                residue.setText(book.getNumberRemaining().toString());
//                设置文本框背景 颜色：结实的树
                returnTime.setBackgroundColor(0xCCDEB887);
                returnTime.setHint("请选择归还日期");
//                日期选择触发器
                returnTime.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            showDatePickDlg();
                            return true;
                        }
                        return false;
                    }
                });
//                进入文本编辑框焦点触发日期选择器
                returnTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            showDatePickDlg();
                        }
                    }
                });
                break;
            case R.id.borrow_book_btn: // 预约图书
//                获取搜索的图书名称或书号
                TextView borrowId = findViewById(R.id.book_id);
                String borrowId2 = borrowId.getText().toString();
                if (Objects.isNull(borrowId2) || borrowId2.equals("")) {
                    Toast.makeText(BorrowActivity.this,"请查询需要预约的书籍！",Toast.LENGTH_SHORT).show();
                    break;
                }
//                判断当前登录状态是否正常 此处不需要进行bundle判断，因为onCreate()已经校验了
                Intent intent = getIntent();
                Bundle bundle = intent.getExtras();
                String loginId = (String) bundle.get("loginId");
                if (Objects.isNull(loginId) || loginId.equals("")) {
                    toast = ToastUtil.toastHint(toast,BorrowActivity.this,"当前登录异常,请重新登录!");
                    return;
                }

//                判断是否填写归还日期
                String returnTimeToString = returnTime.getText().toString();
                if (Objects.isNull(returnTimeToString) || returnTimeToString.equals("")) {
                    toast = ToastUtil.toastHint(toast,BorrowActivity.this,"请填写归还日期!");
                    return;
                }

                Log.i("LoginId==========",loginId);
                Log.i("BookId==========",borrowId2);
                Log.i("returnTime==========",returnTimeToString);
//                查询该用户是否已预约该数据
                SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
                Cursor cursor = readableDatabase.query("ACCOUNT_BOOK_RELATION", null, "AID = ? AND BID = ?", new String[]{loginId,borrowId2}, null, null, null);
                List<String> stringList = new ArrayList<>();
                while (cursor.moveToNext()) {
                    String status = cursor.getString(3);
                    stringList.add(status);
                }
                if (stringList.size() > 0) {
                    for (String status : stringList) {
                        if ("0".equals(status) || "1".equals(status)) {
                            toast = ToastUtil.toastHint(toast,BorrowActivity.this,"此书籍你已预约,不能重复预约!");
                            return;
                        }
                    }
                }

                // TODO: 2021/12/19 待预约书籍 (已解决)
//                    更新图书剩余数量
                long update = updateBook(borrowId2);
                if (update == 1) {

                    ContentValues contentValues = new ContentValues();
                    contentValues.put("AID",loginId);
                    contentValues.put("BID",borrowId2);
                    contentValues.put("STATUS",0);
                    contentValues.put("RETURN_TIME",returnTimeToString);
                    contentValues.put("CREATE_TIME", DateUtil.dateString(new Date()));
                    contentValues.put("UPDATE_TIME",DateUtil.dateString(new Date()));
                    long insert = readableDatabase.insert("ACCOUNT_BOOK_RELATION", null, contentValues);
                    if (insert > 0) {
                        Log.i("BorrowActiviy.java","预约成功记录ID："+insert);
                        toast = ToastUtil.toastHint(toast,BorrowActivity.this,"此书籍预约成功!");
                        break;
                    }
                }

                if (update == 2) {
                    toast = ToastUtil.toastHint(toast,BorrowActivity.this,"书籍太火爆喽,已被借空,请随时关注库存!");
                    break;
                }
                toast = ToastUtil.toastHint(toast,BorrowActivity.this,"此书籍预约失败,请重试!");
                break;

            default:
                Toast.makeText(BorrowActivity.this,"违规触发，请联系管理员！",Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 检测当前剩余数量是否小于预约数量，并进行更新或提示
     * @param borrowId2 图书Id
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private long updateBook(String borrowId2) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("BOOK", null, "ID = ? ", new String[]{borrowId2}, null, null, null);
        Book book = null;
        while (cursor.moveToNext()) {
            Integer bookId = Integer.valueOf(cursor.getString(0));
            String bookName = cursor.getString(2);
            String auhtor = cursor.getString(3);
            String press = cursor.getString(4);
            Integer bookNum = null,numberRemaining = null;
            try {
                bookNum = Integer.valueOf(cursor.getString(5));
                numberRemaining = Integer.valueOf(cursor.getString(6));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("BorrowActivity.java","数据转化数字失败，请检查！");
            }
            book = new Book(bookId,bookName,auhtor,press,bookNum,numberRemaining);
        }
        if (Objects.nonNull(book)) {
            ContentValues contentValues = new ContentValues();
            Integer numberRemaining = book.getNumberRemaining() == null ? 0:book.getNumberRemaining();
            if (numberRemaining < 1) {
//                代表库存不足
                return 2;
            }
            contentValues.put("NUMBER_REMAINING",(numberRemaining-1));
            contentValues.put("UPDATE_TIME",DateUtil.dateString(new Date()));
            int update = readableDatabase.update("BOOK", contentValues, "ID = ?", new String[]{borrowId2});
            if (update == 1) {
                return 1;
            }
        }
        return 0;
    }

    /**
     * 弹出日期选择框
     */
    private void showDatePickDlg() {
        Calendar calendar = Calendar.getInstance();
//        获取当前日期
        final int mYear = calendar.get(Calendar.YEAR);
        final int mMonth = calendar.get(Calendar.MONTH);
        final int mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(BorrowActivity.this,
                new OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//                        判断选择年是否小于当前年
                        if (year < mYear) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,BorrowActivity.this,"归还日期不能小于当天,请重新选择！");
                            return;
                        }
//                        判断选择月是否小于当前月
                        if (year == mYear && month < mMonth) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,BorrowActivity.this,"归还日期不能小于当天,请重新选择！");
                            return;
                        }
//                        判断选择日是否小于当前日
                        if (year == mYear && month == mMonth && dayOfMonth < mDayOfMonth) {
                            view.updateDate(mYear, mMonth, mDayOfMonth);
                            toast = ToastUtil.toastHint(toast,BorrowActivity.this,"归还日期不能小于当天,请重新选择！");
                            return;
                        }

                        BorrowActivity.this.returnTime.setText(year+"-"+(month+1)+"-"+dayOfMonth);
                    }
                },
                mYear,
                mMonth,
                mDayOfMonth);
        datePickerDialog.show();
    }


    /**
     * 数据库搜索图书
     * @param borrow_name2 图书名称或图书编号
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private Book searchBook(String borrow_name2) {
        Book book = findByName(borrow_name2);
        if (Objects.isNull(book)) {
            return null;
        }
        return book;
    }

    /**
     * 去往数据库查询数据
     * @param borrow_name2 图书名称或图书编号
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private Book findByName(String borrow_name2) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("BOOK", null, "BOOK_NUMBER = ? OR BOOK_NAME = ? ", new String[]{borrow_name2,borrow_name2}, null, null, null);
        Book book = null;
        while (cursor.moveToNext()) {
            Integer bookId = Integer.valueOf(cursor.getString(0));
            String bookName = cursor.getString(2);
            String auhtor = cursor.getString(3);
            String press = cursor.getString(4);
            Integer bookNum = null,numberRemaining = null;
            try {
                bookNum = Integer.valueOf(cursor.getString(5));
                numberRemaining = Integer.valueOf(cursor.getString(6));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("BorrowActivity.java","数据转化数字失败，请检查！");
            }
            book = new Book(bookId,bookName,auhtor,press,bookNum,numberRemaining);
        }
        if (Objects.nonNull(book)) {
            return book;
        }
        return null;
    }


    /**
     * 模拟访问数据库查询
     * @param bookName
     * @return
     */
    /*@RequiresApi(api = Build.VERSION_CODES.N)
    public Book findByName(String bookName) {
        List<Book> bookList = new ArrayList<>();
        bookList.add(new Book(1,"102323", "语文", "文殊", "中华人民", 100, 80,new Date(),new Date()));
        bookList.add(new Book(2,"2031311", "斗破苍穹", "我爱吃西红柿", "都多啊", 200, 60,new Date(),new Date()));
        bookList.add(new Book(3,"21314","斗罗大陆", "唐家三少", "三少", 300, 180,new Date(),new Date()));
        bookList.add(new Book(4,"20341", "Java从入门到入坑", "詹姆斯~高斯林", "宾夕法", 160, 30,new Date(),new Date()));
        Map<String,Book> map = new HashMap<>();
        map.put("语文",bookList.get(0));
        map.put("斗破苍穹",bookList.get(1));
        map.put("斗罗大陆",bookList.get(2));
        map.put("Java从入门到入坑",bookList.get(3));
        Book book = map.get(bookName);
        if (Objects.isNull(book)) {
            return null;
        }
        return book;

    }*/


}